package com.grademaster.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.CollegePageDto;
import com.grademaster.entity.Colleges;
import com.grademaster.mapper.CollegesMapper;
import com.grademaster.service.CollegesService;
import com.grademaster.util.LoginUtil;
import com.grademaster.util.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
* @author Administrator
* @description 针对表【colleges(学院表)】的数据库操作Service实现
* @createDate 2024-06-25 13:56:57
*/
@Service
public class CollegesServiceImpl extends ServiceImpl<CollegesMapper, Colleges>
    implements CollegesService {

    /**
     * 查询所有学院
     *
     * @return
     */
    @Override
    public R getAllColleges() {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        return R.success(this.list());
    }

    /**
     * 分页查询学院
     *
     * @param collegePageDto
     * @return
     */
    @Override
    public R getAllCollegesByPage(CollegePageDto collegePageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        Page<Colleges> page = new Page<>(collegePageDto.getPage(), collegePageDto.getPageSize());
        LambdaQueryWrapper<Colleges> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否有查询
        queryWrapper.eq(StringUtils.isNotEmpty(collegePageDto.getCollegeName()),Colleges::getCollegeName, collegePageDto.getCollegeName());
        return R.success(this.page(page,queryWrapper));
    }
    /**
     * 导出学院
     *
     * @param collegePageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(CollegePageDto collegePageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return ResponseEntity.badRequest().build();
        }
        Page<Colleges> page = new Page<>(1, 2000);
        LambdaQueryWrapper<Colleges> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否有查询
        queryWrapper.eq(StringUtils.isNotEmpty(collegePageDto.getCollegeName()),Colleges::getCollegeName, collegePageDto.getCollegeName());
        Page<Colleges> page1 = this.page(page, queryWrapper);
        List<Colleges> records = page1.getRecords();
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Colleges"
        Sheet sheet = workbook.createSheet("Colleges");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"学院ID", "学院名称"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (Colleges college : records) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(college.getCollegeId());
            row.createCell(1).setCellValue(college.getCollegeName());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=colleges.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);

    }

    /**
     * 添加或修改学院
     *
     * @return
     */
    @Override
    public R addorEditCollege(Colleges colleges) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        if (colleges.getCollegeId()!=null){
            //修改学院
            return R.success(this.updateById(colleges));
        }
        //添加学院
        return R.success(this.save(colleges));
    }

    /**
     * 删除学院
     *
     * @param collegeId
     * @return
     */
    @Override
    public R deleteCollege(String collegeId) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        String[] ids = collegeId.split(",");
        for (String id : ids) {
            this.removeById(id);
        }
        return R.success("删除成功");
    }


}




